//
// @Author: zhengqi Wu
// @Description:
// @Version: 1.0.0
// @Date: 2021/3/24 15:59 上午
// @Copyright: MIN-Group；国家重大科技基础设施——未来网络北大实验室；深圳市信息论与未来网络重点实验室
//

const encoding = require("../encoding")
const {LpPacketHeader} = require('../component/LpPacketHeader')
const {Payload} = require('../component/Payload')
class LpPacket extends encoding.IEncodingAble{
    constructor() {
        super();
        this.LpPacketHeader = new LpPacketHeader()
        this.Payload = new Payload()
    }

    /**
     * @description 将 LpPacket 线速编码为一个 TLV
     * @param enc
     * @returns {number}
     */
    wireEncode(enc){
        let totalLength = 0
        try {
            // 编码TLV-VALUE
            let tmpLen = this.LpPacketHeader.wireEncode(enc)
            // DONE 错误处理
            totalLength += tmpLen
            // Fragment
            tmpLen = this.Payload.wireEncode(enc)
            totalLength += tmpLen

            // 编码TLV-LENGTH
            tmpLen = enc.prependVarNumber(totalLength)
            // DONE 错误处理
            totalLength += tmpLen

            // 编码 TLV-TYPE
            tmpLen = enc.prependVarNumber(encoding.tlv.ComponentType.TlvLpPacket)
            // DONE 错误处理
            totalLength += tmpLen

            return totalLength
        } catch (e) {
            throw e
        }
        
    }

    /**
     * @description 从 Block TLV 中解码出一个 LpPacket
     * @param block
     */
    wireDecode(block) {
        try {
            if (encoding.tlv.expectType(block.getType(), encoding.tlv.ComponentType.TlvLpPacket)) {
                block.parseSubElements()
                let elements = block.getSubElements()
                for (let i = 0; i < elements.length; i++) {
                    let element = elements[i]
                    switch (element.getType()) {
                        case encoding.tlv.ComponentType.TlvLpPacketHeader:
                            this.LpPacketHeader.wireDecode(element)
                            break
                        case encoding.tlv.ComponentType.TlvPayload:
                            this.Payload.wireDecode(element)
                            break
                    }
                }
            }
        } catch (e) {
            throw e
        }
        
    }
}

module.exports = LpPacket